18817535bSAndreas Gohr<?php 28817535bSAndreas Gohr 38817535bSAndreas Gohrnamespace dokuwiki\plugin\aichat; 48817535bSAndreas Gohr 58817535bSAndreas Gohruse dokuwiki\Search\Indexer; 68817535bSAndreas Gohruse Hexogen\KDTree\FSKDTree; 78817535bSAndreas Gohruse Hexogen\KDTree\FSTreePersister; 88817535bSAndreas Gohruse Hexogen\KDTree\Item; 98817535bSAndreas Gohruse Hexogen\KDTree\ItemFactory; 108817535bSAndreas Gohruse Hexogen\KDTree\ItemList; 118817535bSAndreas Gohruse Hexogen\KDTree\KDTree; 128817535bSAndreas Gohruse Hexogen\KDTree\NearestSearch; 138817535bSAndreas Gohruse Hexogen\KDTree\Point; 142ecc089aSAndreas Gohruse splitbrain\phpcli\CLI; 158817535bSAndreas Gohruse TikToken\Encoder; 168817535bSAndreas Gohruse Vanderlee\Sentence\Sentence; 178817535bSAndreas Gohr 189da5f0dfSAndreas Gohr/** 199da5f0dfSAndreas Gohr * Manage the embeddings index 209da5f0dfSAndreas Gohr * 219da5f0dfSAndreas Gohr * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from 229da5f0dfSAndreas Gohr * OpenAI and stored in a K-D Tree, chunk data is written to the file system. 239da5f0dfSAndreas Gohr */ 248817535bSAndreas Gohrclass Embeddings 258817535bSAndreas Gohr{ 268817535bSAndreas Gohr 27c4584168SAndreas Gohr const MAX_TOKEN_LEN = 1000; 288817535bSAndreas Gohr const INDEX_NAME = 'aichat'; 298817535bSAndreas Gohr const INDEX_FILE = 'index.bin'; 308817535bSAndreas Gohr 312ecc089aSAndreas Gohr /** @var OpenAI */ 328817535bSAndreas Gohr protected $openAI; 332ecc089aSAndreas Gohr /** @var CLI|null */ 342ecc089aSAndreas Gohr protected $logger; 358817535bSAndreas Gohr 362ecc089aSAndreas Gohr /** 372ecc089aSAndreas Gohr * @param OpenAI $openAI 382ecc089aSAndreas Gohr */ 392ecc089aSAndreas Gohr public function __construct(OpenAI $openAI) 408817535bSAndreas Gohr { 418817535bSAndreas Gohr $this->openAI = $openAI; 422ecc089aSAndreas Gohr } 432ecc089aSAndreas Gohr 442ecc089aSAndreas Gohr /** 452ecc089aSAndreas Gohr * Add a logger instance 462ecc089aSAndreas Gohr * 472ecc089aSAndreas Gohr * @param CLI $logger 482ecc089aSAndreas Gohr * @return void 492ecc089aSAndreas Gohr */ 502ecc089aSAndreas Gohr public function setLogger(CLI $logger) 512ecc089aSAndreas Gohr { 528817535bSAndreas Gohr $this->logger = $logger; 538817535bSAndreas Gohr } 548817535bSAndreas Gohr 552ecc089aSAndreas Gohr /** 562ecc089aSAndreas Gohr * Create a new K-D Tree from all pages 572ecc089aSAndreas Gohr * 582ecc089aSAndreas Gohr * Deletes the existing index 592ecc089aSAndreas Gohr * 602ecc089aSAndreas Gohr * @return void 612ecc089aSAndreas Gohr * @throws \Hexogen\KDTree\Exception\ValidationException 622ecc089aSAndreas Gohr */ 638817535bSAndreas Gohr public function createNewIndex() 648817535bSAndreas Gohr { 658817535bSAndreas Gohr io_rmdir($this->getStorageDir(), true); // delete old index 668817535bSAndreas Gohr 678817535bSAndreas Gohr $indexer = new Indexer(); 688817535bSAndreas Gohr $pages = $indexer->getPages(); 698817535bSAndreas Gohr $itemCount = 0; 708817535bSAndreas Gohr 718817535bSAndreas Gohr $itemList = new ItemList(1536); 728817535bSAndreas Gohr foreach ($pages as $page) { 738817535bSAndreas Gohr if (!page_exists($page)) continue; 74*6f9744f7SAndreas Gohr if (isHiddenPage($page)) continue; 758817535bSAndreas Gohr $text = rawWiki($page); 768817535bSAndreas Gohr $chunks = $this->splitIntoChunks($text); 778817535bSAndreas Gohr $meta = [ 788817535bSAndreas Gohr 'pageid' => $page, 798817535bSAndreas Gohr ]; 808817535bSAndreas Gohr foreach ($chunks as $chunk) { 818817535bSAndreas Gohr $embedding = $this->openAI->getEmbedding($chunk); 828817535bSAndreas Gohr $item = new Item($itemCount++, $embedding); 838817535bSAndreas Gohr $itemList->addItem($item); 848817535bSAndreas Gohr $this->saveChunk($item->getId(), $chunk, $meta); 858817535bSAndreas Gohr } 868817535bSAndreas Gohr if ($this->logger) { 878817535bSAndreas Gohr $this->logger->success('Split {id} into {count} chunks', ['id' => $page, 'count' => count($chunks)]); 888817535bSAndreas Gohr } 898817535bSAndreas Gohr } 908817535bSAndreas Gohr 918817535bSAndreas Gohr $tree = new KDTree($itemList); 928817535bSAndreas Gohr if ($this->logger) { 938817535bSAndreas Gohr $this->logger->success('Created index with {count} items', ['count' => $tree->getItemCount()]); 948817535bSAndreas Gohr } 958817535bSAndreas Gohr $persister = new FSTreePersister($this->getStorageDir()); 968817535bSAndreas Gohr $persister->convert($tree, self::INDEX_FILE); 978817535bSAndreas Gohr } 988817535bSAndreas Gohr 999e81bea7SAndreas Gohr /** 1009e81bea7SAndreas Gohr * Do a nearest neighbor search for chunks similar to the given question 1019e81bea7SAndreas Gohr * 1029e81bea7SAndreas Gohr * Returns only chunks the current user is allowed to read, may return an empty result. 1039e81bea7SAndreas Gohr * 1049e81bea7SAndreas Gohr * @param string $query The question 1059e81bea7SAndreas Gohr * @param int $limit The number of results to return 1069e81bea7SAndreas Gohr * @return array 1079e81bea7SAndreas Gohr * @throws \Exception 1089e81bea7SAndreas Gohr */ 1098817535bSAndreas Gohr public function getSimilarChunks($query, $limit = 4) 1108817535bSAndreas Gohr { 1119e81bea7SAndreas Gohr global $auth; 1128817535bSAndreas Gohr $embedding = $this->openAI->getEmbedding($query); 1138817535bSAndreas Gohr 1148817535bSAndreas Gohr $file = $this->getStorageDir() . self::INDEX_FILE; 1158817535bSAndreas Gohr $fsTree = new FSKDTree($file, new ItemFactory()); 1168817535bSAndreas Gohr $fsSearcher = new NearestSearch($fsTree); 1179e81bea7SAndreas Gohr $items = $fsSearcher->search(new Point($embedding), $limit * 2); // we get twice as many as needed 1188817535bSAndreas Gohr 1198817535bSAndreas Gohr $result = []; 1208817535bSAndreas Gohr foreach ($items as $item) { 1219e81bea7SAndreas Gohr $chunk = $this->loadChunk($item->getId()); 1229e81bea7SAndreas Gohr // filter out chunks the user is not allowed to read 1239e81bea7SAndreas Gohr if ($auth && auth_quickaclcheck($chunk['meta']['pageid']) < AUTH_READ) continue; 1249e81bea7SAndreas Gohr $result[] = $chunk; 1259e81bea7SAndreas Gohr if (count($result) >= $limit) break; 1268817535bSAndreas Gohr } 1278817535bSAndreas Gohr return $result; 1288817535bSAndreas Gohr } 1298817535bSAndreas Gohr 1308817535bSAndreas Gohr /** 1318817535bSAndreas Gohr * @param $text 1328817535bSAndreas Gohr * @return array 1338817535bSAndreas Gohr * @throws \Exception 1348817535bSAndreas Gohr * @todo maybe add overlap support 1358817535bSAndreas Gohr * @todo support splitting too long sentences 1368817535bSAndreas Gohr */ 1378817535bSAndreas Gohr protected function splitIntoChunks($text) 1388817535bSAndreas Gohr { 1398817535bSAndreas Gohr $sentenceSplitter = new Sentence(); 1408817535bSAndreas Gohr $tiktok = new Encoder(); 1418817535bSAndreas Gohr 1428817535bSAndreas Gohr $chunks = []; 1438817535bSAndreas Gohr $sentences = $sentenceSplitter->split($text); 1448817535bSAndreas Gohr 1458817535bSAndreas Gohr $chunklen = 0; 1468817535bSAndreas Gohr $chunk = ''; 1478817535bSAndreas Gohr while ($sentence = array_shift($sentences)) { 1488817535bSAndreas Gohr $slen = count($tiktok->encode($sentence)); 1498817535bSAndreas Gohr if ($slen > self::MAX_TOKEN_LEN) { 1508817535bSAndreas Gohr // sentence is too long, we need to split it further 1518817535bSAndreas Gohr throw new \Exception('Sentence too long, splitting not implemented yet'); 1528817535bSAndreas Gohr } 1538817535bSAndreas Gohr 1548817535bSAndreas Gohr if ($chunklen + $slen < self::MAX_TOKEN_LEN) { 1558817535bSAndreas Gohr // add to current chunk 1568817535bSAndreas Gohr $chunk .= $sentence; 1578817535bSAndreas Gohr $chunklen += $slen; 1588817535bSAndreas Gohr } else { 1598817535bSAndreas Gohr // start new chunk 1608817535bSAndreas Gohr $chunks[] = $chunk; 1618817535bSAndreas Gohr $chunk = $sentence; 1628817535bSAndreas Gohr $chunklen = $slen; 1638817535bSAndreas Gohr } 1648817535bSAndreas Gohr } 1658817535bSAndreas Gohr $chunks[] = $chunk; 1668817535bSAndreas Gohr 1678817535bSAndreas Gohr return $chunks; 1688817535bSAndreas Gohr } 1698817535bSAndreas Gohr 1709da5f0dfSAndreas Gohr /** 1719da5f0dfSAndreas Gohr * Store additional chunk data in the file system 1729da5f0dfSAndreas Gohr * 1739da5f0dfSAndreas Gohr * @param int $id The chunk id in the K-D tree 1749da5f0dfSAndreas Gohr * @param string $text raw text of the chunk 1759da5f0dfSAndreas Gohr * @param array $meta meta data to store with the chunk 1769da5f0dfSAndreas Gohr * @return void 1779da5f0dfSAndreas Gohr */ 1788817535bSAndreas Gohr public function saveChunk($id, $text, $meta = []) 1798817535bSAndreas Gohr { 1808817535bSAndreas Gohr $data = [ 1818817535bSAndreas Gohr 'id' => $id, 1828817535bSAndreas Gohr 'text' => $text, 1838817535bSAndreas Gohr 'meta' => $meta, 1848817535bSAndreas Gohr ]; 1858817535bSAndreas Gohr 1868817535bSAndreas Gohr $chunkfile = $this->getStorageDir('chunk') . $id . '.json'; 1878817535bSAndreas Gohr io_saveFile($chunkfile, json_encode($data)); 1888817535bSAndreas Gohr } 1898817535bSAndreas Gohr 1909da5f0dfSAndreas Gohr /** 1919da5f0dfSAndreas Gohr * Load chunk data from the file system 1929da5f0dfSAndreas Gohr * 1939da5f0dfSAndreas Gohr * @param int $id 1949da5f0dfSAndreas Gohr * @return array The chunk data [id, text, meta => []] 1959da5f0dfSAndreas Gohr */ 1968817535bSAndreas Gohr public function loadChunk($id) 1978817535bSAndreas Gohr { 1988817535bSAndreas Gohr $chunkfile = $this->getStorageDir('chunk') . $id . '.json'; 1998817535bSAndreas Gohr return json_decode(io_readFile($chunkfile, false), true); 2008817535bSAndreas Gohr } 2018817535bSAndreas Gohr 2029da5f0dfSAndreas Gohr /** 2039da5f0dfSAndreas Gohr * Return the path to where the K-D tree and chunk data is stored 2049da5f0dfSAndreas Gohr * 2059da5f0dfSAndreas Gohr * @param string $subdir 2069da5f0dfSAndreas Gohr * @return string 2079da5f0dfSAndreas Gohr */ 2088817535bSAndreas Gohr protected function getStorageDir($subdir = '') 2098817535bSAndreas Gohr { 2108817535bSAndreas Gohr global $conf; 2118817535bSAndreas Gohr $dir = $conf['indexdir'] . '/' . self::INDEX_NAME . '/'; 2128817535bSAndreas Gohr if ($subdir) $dir .= $subdir . '/'; 2138817535bSAndreas Gohr io_mkdir_p($dir); 2148817535bSAndreas Gohr return $dir; 2158817535bSAndreas Gohr } 2168817535bSAndreas Gohr} 217