BxBaseStudioAgentsVectorStore.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 UnaView UNA Studio Representation classes
  7. * @ingroup UnaStudio
  8. * @{
  9. */
  10. class BxBaseStudioAgentsVectorStore extends BxDolStudioAgentsInstruments
  11. {
  12. protected $_sUrlPage;
  13. protected $_aDataExt = [
  14. 'txt' => 'getFileContentPlain',
  15. 'md' => 'getFileContentPlain',
  16. 'html' => 'getFileContentHtml',
  17. ];
  18. public function __construct ($aOptions, $oTemplate = false)
  19. {
  20. parent::__construct ($aOptions, $oTemplate);
  21. $this->_sUrlPage = BX_DOL_URL_STUDIO . 'agents.php?page=vector_store';
  22. }
  23. public function performActionDuplicate()
  24. {
  25. $aVectorStore = $this->_oDb->getVectorStoreById((int)$this->_getId());
  26. if ($this->_isUnaProxyKnowledge($aVectorStore))
  27. return echoJson(['msg' => _t('_sys_txt_error_occured')]);
  28. return parent::_performActionDuplicate('getVectorStoreById', 'insertVectorStore');
  29. }
  30. public function performActionAddData()
  31. {
  32. $sAction = 'add_data';
  33. $iId = $this->_getId();
  34. $aVectorStore = $this->_oDb->getVectorStoreById($iId);
  35. if ($this->_isUnaProxyKnowledge($aVectorStore))
  36. return echoJson(['msg' => _t('_sys_txt_error_occured')]);
  37. $aForm = $this->_getFormAddData($sAction, $aVectorStore);
  38. $oForm = new BxTemplFormView($aForm);
  39. $oForm->initChecker();
  40. if($oForm->isSubmittedAndValid() && isset($_FILES['files'])) {
  41. $iFilesAdded = 0;
  42. foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
  43. $sFileName = $_FILES['files']['name'][$key];
  44. $sFileType = $_FILES['files']['type'][$key];
  45. $sFileSize = $_FILES['files']['size'][$key];
  46. $sFileTmpName = $_FILES['files']['tmp_name'][$key];
  47. $sMetadata = $oForm->getCleanValue('metadata');
  48. $iVectorStoreId = $oForm->getCleanValue('vector_store_id');
  49. $sSettings = json_encode([
  50. 'chunk_size' => $oForm->getCleanValue('chunk_size'),
  51. 'delimeter' => trim($oForm->getCleanValue('delimeter')),
  52. 'overlap' => $oForm->getCleanValue('overlap'),
  53. ]);
  54. $sExt = pathinfo($sFileName, PATHINFO_EXTENSION);
  55. $sMethod = isset($this->_aDataExt[$sExt]) ? $this->_aDataExt[$sExt] : 'getFileContentPlain';
  56. $sContent = $this->$sMethod($sFileTmpName);
  57. if (empty($sContent)) {
  58. continue;
  59. }
  60. $bRet = $this->_oDb->addVectorStoreData ($iVectorStoreId, 'custom', $sFileName, (int)$sFileSize, $sMetadata, $sSettings, $sContent);
  61. if ($bRet) {
  62. $iFilesAdded++;
  63. }
  64. }
  65. return echoJson(['toast' => _t('_sys_agents_vector_store_data_queued', $iFilesAdded)]);
  66. if($oForm->add($iId) === false)
  67. return echoJson(['msg' => _t('_sys_txt_error_occured')]);
  68. return echoJson(['grid' => $this->getCode(false), 'blink' => $iId]);
  69. }
  70. $sFormId = $oForm->getId();
  71. $sForm = $oForm->getCode(true);
  72. $sContent = BxTemplStudioFunctions::getInstance()->popupBox($sFormId . '_popup_' . $sAction, _t('_sys_agents_vector_store_popup_add_data'), $this->_oTemplate->parseHtmlByName('agents_agents_form.html', [
  73. 'form_id' => $sFormId,
  74. 'form' => $sForm,
  75. 'object' => $this->_sObject,
  76. 'action' => $sAction
  77. ]));
  78. return echoJson(['popup' => ['html' => $sContent, 'options' => ['closeOnOuterClick' => false]]]);
  79. }
  80. public function performActionEdit()
  81. {
  82. $aVectorStore = $this->_oDb->getVectorStoreById((int)$this->_getId());
  83. if ($this->_isUnaProxyKnowledge($aVectorStore))
  84. return echoJson(['msg' => _t('_sys_txt_error_occured')]);
  85. return $this->_performActionEdit('getVectorStoreById', '_sys_agents_vector_store_popup_edit');
  86. }
  87. public function performActionFiles()
  88. {
  89. $iId = $this->_getId();
  90. $aVectorStore = $this->_oDb->getVectorStoreById($iId);
  91. $oGrid = BxDolGrid::getObjectInstance('sys_studio_agents_vector_store_data');
  92. $oGrid->addMarkers(['vector_store_id' => $iId]);
  93. $oGrid->setBrowseParams(['vector_store_id' => $iId]);
  94. $sGrid = $oGrid->getCode();
  95. $sContent = BxTemplStudioFunctions::getInstance()->popupBox('popup_files_' . $iId, _t('_sys_agents_vector_store_popup_files'), $this->_oTemplate->parseHtmlByName('agents_popup_grid.html', [
  96. 'grid' => $sGrid,
  97. ]));
  98. return echoJson(['popup' => ['html' => $sContent, 'options' => ['closeOnOuterClick' => false]]]);
  99. }
  100. protected function _getForm($sAction = '', $aVectorStore = [])
  101. {
  102. $sJsObject = $this->getPageJsObject();
  103. if (empty($aVectorStore['params_user']))
  104. $aVectorStore['params_user'] = $aVectorStore['params'] ?? '';
  105. $sParams = is_string($aVectorStore['params_user']) ? $aVectorStore['params_user'] : '';
  106. $data = $sParams !== '' ? json_decode($sParams, true) : null;
  107. $aVectorStore['params_user'] = is_array($data) ? json_encode($data, JSON_PRETTY_PRINT) : $sParams;
  108. $oParsedown = new Parsedown();
  109. $oParsedown->setSafeMode(false);
  110. $sDocs = $oParsedown->text($aVectorStore['docs']);
  111. $aEmbeddingProviders = ['' => _t('_sys_please_select')];
  112. $a = BxDolAi::getInstance()->getModels(['capabilities' => 'embeddings', 'active' => true]);
  113. foreach ($a as $k => $v) {
  114. $aEmbeddingProviders[$k] = $v;
  115. }
  116. $aForm = [
  117. 'form_attrs' => [
  118. 'id' => 'bx_std_agents_vector_store_' . $sAction,
  119. 'action' => BX_DOL_URL_ROOT . 'grid.php?o=sys_studio_agents_vector_store&a=' . $sAction,
  120. 'method' => 'post',
  121. ],
  122. 'params' => array (
  123. 'db' => array(
  124. 'table' => 'sys_agents_vector_store',
  125. 'key' => 'id',
  126. 'submit_name' => 'do_submit',
  127. ),
  128. ),
  129. 'inputs' => [
  130. 'docs' => [
  131. 'type' => 'custom',
  132. 'name' => 'docs',
  133. 'caption' => '',
  134. 'content' => $sDocs,
  135. ],
  136. 'title' => [
  137. 'type' => 'text',
  138. 'name' => 'title',
  139. 'caption' => _t('_sys_agents_field_title'),
  140. 'required' => true,
  141. 'value' => !empty($aVectorStore['title']) ? $aVectorStore['title'] : '',
  142. 'db' => [
  143. 'pass' => 'Xss'
  144. ]
  145. ],
  146. 'embedding_provider_id' => [
  147. 'type' => 'select',
  148. 'name' => 'embedding_provider_id',
  149. 'caption' => _t('_sys_agents_vector_store_field_embedding_provider_id'),
  150. 'info' => _t('_sys_agents_vector_store_field_embedding_provider_id_info'),
  151. 'value' => !empty($aVectorStore['embedding_provider_id']) ? $aVectorStore['embedding_provider_id'] : '',
  152. 'values' => $aEmbeddingProviders,
  153. 'db' => [
  154. 'pass' => 'Int'
  155. ]
  156. ],
  157. 'topk' => [
  158. 'type' => 'text',
  159. 'name' => 'topk',
  160. 'caption' => _t('_sys_agents_vector_store_field_topk'),
  161. 'info' => _t('_sys_agents_vector_store_field_topk_info'),
  162. 'required' => true,
  163. 'value' => !empty($aVectorStore['topk']) ? $aVectorStore['topk'] : '',
  164. 'db' => [
  165. 'pass' => 'Int'
  166. ]
  167. ],
  168. 'params_user' => [
  169. 'type' => 'textarea',
  170. 'name' => 'params_user',
  171. 'caption' => _t('_sys_agents_vector_store_field_params'),
  172. 'info' => _t('_sys_agents_vector_store_field_params_info'),
  173. 'required' => false,
  174. 'value' => !empty($aVectorStore['params_user']) ? $aVectorStore['params_user'] : '',
  175. 'checker' => [
  176. 'func' => 'Json',
  177. 'params' => ['allow_empty' => true],
  178. 'error' => _t('_sys_agents_json_field_err'),
  179. ],
  180. 'db' => [
  181. 'pass' => 'All'
  182. ]
  183. ],
  184. 'submit' => $this->_getFormControls(),
  185. ]
  186. ];
  187. if ($sAction === 'edit' && $this->_isUnaProxyKnowledge($aVectorStore)) {
  188. foreach (['title', 'topk', 'params_user'] as $sField)
  189. $aForm['inputs'][$sField]['attrs']['readonly'] = 'readonly';
  190. $aForm['inputs']['embedding_provider_id']['attrs']['disabled'] = 'disabled';
  191. }
  192. return $aForm;
  193. }
  194. protected function _getFormAddData(string $sAction, array $aVectorStore)
  195. {
  196. $sJsObject = $this->getPageJsObject();
  197. $aExt = array_keys($this->_aDataExt);
  198. $sExtList = '.' . implode(', .', $aExt);
  199. return [
  200. 'form_attrs' => [
  201. 'id' => 'bx_std_agents_vector_store_data_' . $sAction,
  202. 'action' => BX_DOL_URL_ROOT . 'grid.php?o=sys_studio_agents_vector_store&a=' . $sAction,
  203. 'method' => 'post',
  204. ],
  205. 'params' => array (
  206. 'db' => array(
  207. 'table' => 'sys_agents_vector_store_data',
  208. 'key' => 'id',
  209. 'submit_name' => 'do_submit',
  210. ),
  211. ),
  212. 'inputs' => [
  213. 'vector_store_id' => [
  214. 'type' => 'hidden',
  215. 'name' => 'vector_store_id',
  216. 'value' => $aVectorStore ? $aVectorStore['id'] : 0,
  217. ],
  218. 'chunk_size' => [
  219. 'type' => 'text',
  220. 'name' => 'chunk_size',
  221. 'caption' => _t('_sys_agents_vector_store_field_chunk_size'),
  222. 'info' => _t('_sys_agents_vector_store_field_chunk_size_info'),
  223. 'required' => true,
  224. 'value' => 512,
  225. 'db' => [
  226. 'pass' => 'Int'
  227. ]
  228. ],
  229. 'delimeter' => [
  230. 'type' => 'text',
  231. 'name' => 'delimeter',
  232. 'caption' => _t('_sys_agents_vector_store_field_delimeter'),
  233. 'info' => _t('_sys_agents_vector_store_field_delimeter_info'),
  234. 'required' => true,
  235. 'value' => '.',
  236. 'db' => [
  237. 'pass' => 'Xss'
  238. ]
  239. ],
  240. 'overlap' => [
  241. 'type' => 'text',
  242. 'name' => 'overlap',
  243. 'caption' => _t('_sys_agents_vector_store_field_overlap'),
  244. 'info' => _t('_sys_agents_vector_store_field_overlap_info'),
  245. 'required' => true,
  246. 'value' => 2,
  247. 'db' => [
  248. 'pass' => 'Int'
  249. ]
  250. ],
  251. 'metadata' => [
  252. 'type' => 'textarea',
  253. 'name' => 'metadata',
  254. 'caption' => _t('_sys_agents_vector_store_field_metadata'),
  255. 'info' => _t('_sys_agents_vector_store_field_metadata_info'),
  256. 'required' => false,
  257. 'checker' => [
  258. 'func' => 'Json',
  259. 'params' => ['allow_empty' => true],
  260. 'error' => _t('_sys_agents_json_field_err'),
  261. ],
  262. 'db' => [
  263. 'pass' => 'All'
  264. ]
  265. ],
  266. 'files' => [
  267. 'attrs' => [
  268. 'multiple' => true,
  269. 'accept' => $sExtList
  270. ],
  271. 'type' => 'file',
  272. 'name' => 'files[]',
  273. 'caption' => _t('_sys_agents_vector_store_field_files'),
  274. 'caption_info' => _t('_sys_agents_vector_store_field_files_info'),
  275. 'required' => true,
  276. ],
  277. 'submit' => $this->_getFormControls(),
  278. ]
  279. ];
  280. }
  281. protected function getFileContentPlain($sFilePath)
  282. {
  283. return file_get_contents($sFilePath);
  284. }
  285. protected function getFileContentHtml($sFilePath)
  286. {
  287. $s = file_get_contents($sFilePath);
  288. $html = new \Html2Text\Html2Text($s);
  289. return $html->getText();
  290. }
  291. protected function _getCellEmbeddingProviderId($mixedValue, $sKey, $aField, $aRow)
  292. {
  293. if ($this->_isUnaProxyKnowledge($aRow))
  294. return parent::_getCellDefault('', $sKey, $aField, $aRow);
  295. $aProvider = $this->_oDb->getModelsBy(['sample' => 'id', 'id' => $mixedValue]);
  296. $s = !empty($aProvider) ? $aProvider['title'] : _t('_undefined');
  297. return parent::_getCellDefault($s, $sKey, $aField, $aRow);
  298. }
  299. protected function _getCellFilesNum($mixedValue, $sKey, $aField, $aRow)
  300. {
  301. if ($this->_isUnaProxyKnowledge($aRow)) {
  302. $sLabel = _t('_sys_not_available');
  303. $s = '<i class="sys-icon circle col-gray" role="img" aria-label="' . bx_html_attribute($sLabel) . '" title="' . bx_html_attribute($sLabel) . '"></i>';
  304. return parent::_getCellDefault($s, $sKey, $aField, $aRow);
  305. }
  306. $s = $this->_oDb->getVectorStoreDataNum($aRow['id']);
  307. if ((int)$s !== 0)
  308. $s = '<a href="javascript:void(0)" onclick="glGrids.' . $this->_sObject . '.actionWithId (' . $aRow['id'] . ', \'files\', {}, \'\', false, 0);">' . $s . '</a>';
  309. return parent::_getCellDefault($s, $sKey, $aField, $aRow);
  310. }
  311. protected function _delete ($mixedId)
  312. {
  313. $aModel = $this->_oDb->getVectorStoreById($mixedId);
  314. if (empty($aModel) || $this->_isUnaProxyKnowledge($aModel) || $aModel['duplicate'] == 0)
  315. return false;
  316. // TODO: delete actual vector store data if needed
  317. return parent::_delete($mixedId);
  318. }
  319. protected function _isUnaProxyKnowledge($aVectorStore)
  320. {
  321. return is_array($aVectorStore) && ($aVectorStore['type'] ?? '') === 'una-proxy';
  322. }
  323. protected function _getActionAddData($sType, $sKey, $a, $isSmall = false, $isDisabled = false, $aRow = [])
  324. {
  325. if ($this->_isUnaProxyKnowledge($aRow))
  326. return '';
  327. return parent::_getActionDefault($sType, $sKey, $a, $isSmall, $isDisabled, $aRow);
  328. }
  329. protected function _getActionDuplicate($sType, $sKey, $a, $isSmall = false, $isDisabled = false, $aRow = [])
  330. {
  331. if ($this->_isUnaProxyKnowledge($aRow))
  332. return '';
  333. return parent::_getActionDefault($sType, $sKey, $a, $isSmall, $isDisabled, $aRow);
  334. }
  335. protected function _getActionEdit($sType, $sKey, $a, $isSmall = false, $isDisabled = false, $aRow = [])
  336. {
  337. if ($this->_isUnaProxyKnowledge($aRow))
  338. return '';
  339. return parent::_getActionDefault($sType, $sKey, $a, $isSmall, $isDisabled, $aRow);
  340. }
  341. protected function _getActionDelete($sType, $sKey, $a, $isSmall = false, $isDisabled = false, $aRow = [])
  342. {
  343. if ($this->_isUnaProxyKnowledge($aRow))
  344. return '';
  345. return parent::_getActionDelete($sType, $sKey, $a, $isSmall, $isDisabled, $aRow);
  346. }
  347. }
  348. /** @} */