BxBaseStudioAgentsVectorStore.php 13 KB

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