BxBaseStudioAgentsVectorStore.php 15 KB

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