18817535bSAndreas Gohr<?php 28817535bSAndreas Gohr 38817535bSAndreas Gohrnamespace dokuwiki\plugin\aichat; 48817535bSAndreas Gohr 5f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Model\AbstractModel; 6f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\AbstractStorage; 78817535bSAndreas Gohruse dokuwiki\Search\Indexer; 82ecc089aSAndreas Gohruse splitbrain\phpcli\CLI; 98817535bSAndreas Gohruse TikToken\Encoder; 108817535bSAndreas Gohruse Vanderlee\Sentence\Sentence; 118817535bSAndreas Gohr 129da5f0dfSAndreas Gohr/** 139da5f0dfSAndreas Gohr * Manage the embeddings index 149da5f0dfSAndreas Gohr * 159da5f0dfSAndreas Gohr * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from 167ee8b02dSAndreas Gohr * OpenAI and stored in the Storage backend. 179da5f0dfSAndreas Gohr */ 188817535bSAndreas Gohrclass Embeddings 198817535bSAndreas Gohr{ 2068908844SAndreas Gohr /** @var int maximum overlap between chunks in tokens */ 2168908844SAndreas Gohr const MAX_OVERLAP_LEN = 200; 228817535bSAndreas Gohr 23f6ef2e50SAndreas Gohr /** @var AbstractModel */ 24f6ef2e50SAndreas Gohr protected $model; 252ecc089aSAndreas Gohr /** @var CLI|null */ 262ecc089aSAndreas Gohr protected $logger; 2768908844SAndreas Gohr /** @var Encoder */ 2868908844SAndreas Gohr protected $tokenEncoder; 298817535bSAndreas Gohr 307ee8b02dSAndreas Gohr /** @var AbstractStorage */ 317ee8b02dSAndreas Gohr protected $storage; 327ee8b02dSAndreas Gohr 3368908844SAndreas Gohr /** @var array remember sentences when chunking */ 3468908844SAndreas Gohr private $sentenceQueue = []; 3568908844SAndreas Gohr 362ecc089aSAndreas Gohr /** 37f6ef2e50SAndreas Gohr * @param AbstractModel $model 382ecc089aSAndreas Gohr */ 39f6ef2e50SAndreas Gohr public function __construct(AbstractModel $model, AbstractStorage $storage) 408817535bSAndreas Gohr { 41f6ef2e50SAndreas Gohr $this->model = $model; 42f6ef2e50SAndreas Gohr $this->storage = $storage; 437ee8b02dSAndreas Gohr } 447ee8b02dSAndreas Gohr 457ee8b02dSAndreas Gohr /** 467ee8b02dSAndreas Gohr * Access storage 477ee8b02dSAndreas Gohr * 487ee8b02dSAndreas Gohr * @return AbstractStorage 497ee8b02dSAndreas Gohr */ 507ee8b02dSAndreas Gohr public function getStorage() 517ee8b02dSAndreas Gohr { 527ee8b02dSAndreas Gohr return $this->storage; 532ecc089aSAndreas Gohr } 542ecc089aSAndreas Gohr 552ecc089aSAndreas Gohr /** 562ecc089aSAndreas Gohr * Add a logger instance 572ecc089aSAndreas Gohr * 582ecc089aSAndreas Gohr * @param CLI $logger 592ecc089aSAndreas Gohr * @return void 602ecc089aSAndreas Gohr */ 612ecc089aSAndreas Gohr public function setLogger(CLI $logger) 622ecc089aSAndreas Gohr { 638817535bSAndreas Gohr $this->logger = $logger; 648817535bSAndreas Gohr } 658817535bSAndreas Gohr 662ecc089aSAndreas Gohr /** 6768908844SAndreas Gohr * Get the token encoder instance 6868908844SAndreas Gohr * 6968908844SAndreas Gohr * @return Encoder 7068908844SAndreas Gohr */ 7168908844SAndreas Gohr public function getTokenEncoder() 7268908844SAndreas Gohr { 7368908844SAndreas Gohr if ($this->tokenEncoder === null) { 7468908844SAndreas Gohr $this->tokenEncoder = new Encoder(); 7568908844SAndreas Gohr } 7668908844SAndreas Gohr return $this->tokenEncoder; 7768908844SAndreas Gohr } 7868908844SAndreas Gohr 7968908844SAndreas Gohr /** 805284515dSAndreas Gohr * Update the embeddings storage 812ecc089aSAndreas Gohr * 82ad38c5fdSAndreas Gohr * @param string $skipRE Regular expression to filter out pages (full RE with delimiters) 835284515dSAndreas Gohr * @param bool $clear Should any existing storage be cleared before updating? 842ecc089aSAndreas Gohr * @return void 855284515dSAndreas Gohr * @throws \Exception 862ecc089aSAndreas Gohr */ 875284515dSAndreas Gohr public function createNewIndex($skipRE = '', $clear = false) 888817535bSAndreas Gohr { 898817535bSAndreas Gohr $indexer = new Indexer(); 908817535bSAndreas Gohr $pages = $indexer->getPages(); 918817535bSAndreas Gohr 92f6ef2e50SAndreas Gohr $this->storage->startCreation($clear); 935aa45b4dSAndreas Gohr foreach ($pages as $pid => $page) { 945aa45b4dSAndreas Gohr $chunkID = $pid * 100; // chunk IDs start at page ID * 100 955aa45b4dSAndreas Gohr 965284515dSAndreas Gohr if ( 975284515dSAndreas Gohr !page_exists($page) || 985284515dSAndreas Gohr isHiddenPage($page) || 994e206c13SAndreas Gohr filesize(wikiFN($page)) < 150 || // skip very small pages 1005284515dSAndreas Gohr ($skipRE && preg_match($skipRE, $page)) 1015284515dSAndreas Gohr ) { 1025284515dSAndreas Gohr // this page should not be in the index (anymore) 1035284515dSAndreas Gohr $this->storage->deletePageChunks($page, $chunkID); 1045284515dSAndreas Gohr continue; 1055284515dSAndreas Gohr } 1065284515dSAndreas Gohr 1077ee8b02dSAndreas Gohr $firstChunk = $this->storage->getChunk($chunkID); 1087ee8b02dSAndreas Gohr if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) { 1095aa45b4dSAndreas Gohr // page is older than the chunks we have, reuse the existing chunks 1107ee8b02dSAndreas Gohr $this->storage->reusePageChunks($page, $chunkID); 11133128f96SAndreas Gohr if ($this->logger) $this->logger->info("Reusing chunks for $page"); 1125aa45b4dSAndreas Gohr } else { 1135aa45b4dSAndreas Gohr // page is newer than the chunks we have, create new chunks 1147ee8b02dSAndreas Gohr $this->storage->deletePageChunks($page, $chunkID); 1157ee8b02dSAndreas Gohr $this->storage->addPageChunks($this->createPageChunks($page, $chunkID)); 1165aa45b4dSAndreas Gohr } 1175aa45b4dSAndreas Gohr } 1187ee8b02dSAndreas Gohr $this->storage->finalizeCreation(); 1195aa45b4dSAndreas Gohr } 1205aa45b4dSAndreas Gohr 1215aa45b4dSAndreas Gohr /** 1227ee8b02dSAndreas Gohr * Split the given page, fetch embedding vectors and return Chunks 1235aa45b4dSAndreas Gohr * 12488305719SAndreas Gohr * Will use the text renderer plugin if available to get the rendered text. 12588305719SAndreas Gohr * Otherwise the raw wiki text is used. 12688305719SAndreas Gohr * 1275aa45b4dSAndreas Gohr * @param string $page Name of the page to split 1287ee8b02dSAndreas Gohr * @param int $firstChunkID The ID of the first chunk of this page 1297ee8b02dSAndreas Gohr * @return Chunk[] A list of chunks created for this page 1305aa45b4dSAndreas Gohr * @throws \Exception 1315aa45b4dSAndreas Gohr */ 1327ee8b02dSAndreas Gohr protected function createPageChunks($page, $firstChunkID) 1335aa45b4dSAndreas Gohr { 1347ee8b02dSAndreas Gohr $chunkList = []; 13588305719SAndreas Gohr 13688305719SAndreas Gohr $textRenderer = plugin_load('renderer', 'text'); 13788305719SAndreas Gohr if ($textRenderer) { 13888305719SAndreas Gohr global $ID; 13988305719SAndreas Gohr $ID = $page; 14088305719SAndreas Gohr $text = p_cached_output(wikiFN($page), 'text', $page); 14188305719SAndreas Gohr } else { 14288305719SAndreas Gohr $text = rawWiki($page); 14388305719SAndreas Gohr } 14488305719SAndreas Gohr 14588305719SAndreas Gohr $parts = $this->splitIntoChunks($text); 1467ee8b02dSAndreas Gohr foreach ($parts as $part) { 14793c1dbf4SAndreas Gohr if (trim($part) == '') continue; // skip empty chunks 14893c1dbf4SAndreas Gohr 149ad38c5fdSAndreas Gohr try { 150f6ef2e50SAndreas Gohr $embedding = $this->model->getEmbedding($part); 151ad38c5fdSAndreas Gohr } catch (\Exception $e) { 152ad38c5fdSAndreas Gohr if ($this->logger) { 153ad38c5fdSAndreas Gohr $this->logger->error( 154ad38c5fdSAndreas Gohr 'Failed to get embedding for chunk of page {page}: {msg}', 155ad38c5fdSAndreas Gohr ['page' => $page, 'msg' => $e->getMessage()] 156ad38c5fdSAndreas Gohr ); 157ad38c5fdSAndreas Gohr } 158ad38c5fdSAndreas Gohr continue; 159ad38c5fdSAndreas Gohr } 1607ee8b02dSAndreas Gohr $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding); 1617ee8b02dSAndreas Gohr $firstChunkID++; 1628817535bSAndreas Gohr } 1638817535bSAndreas Gohr if ($this->logger) { 16493c1dbf4SAndreas Gohr if (count($chunkList)) { 16593c1dbf4SAndreas Gohr $this->logger->success('{id} split into {count} chunks', ['id' => $page, 'count' => count($chunkList)]); 16693c1dbf4SAndreas Gohr } else { 16793c1dbf4SAndreas Gohr $this->logger->warning('{id} could not be split into chunks', ['id' => $page]); 16893c1dbf4SAndreas Gohr } 1698817535bSAndreas Gohr } 1707ee8b02dSAndreas Gohr return $chunkList; 1718817535bSAndreas Gohr } 1728817535bSAndreas Gohr 1739e81bea7SAndreas Gohr /** 1749e81bea7SAndreas Gohr * Do a nearest neighbor search for chunks similar to the given question 1759e81bea7SAndreas Gohr * 1769e81bea7SAndreas Gohr * Returns only chunks the current user is allowed to read, may return an empty result. 17768908844SAndreas Gohr * The number of returned chunks depends on the MAX_CONTEXT_LEN setting. 1789e81bea7SAndreas Gohr * 1799e81bea7SAndreas Gohr * @param string $query The question 1807ee8b02dSAndreas Gohr * @return Chunk[] 1819e81bea7SAndreas Gohr * @throws \Exception 1829e81bea7SAndreas Gohr */ 18368908844SAndreas Gohr public function getSimilarChunks($query) 1848817535bSAndreas Gohr { 1859e81bea7SAndreas Gohr global $auth; 186f6ef2e50SAndreas Gohr $vector = $this->model->getEmbedding($query); 1878817535bSAndreas Gohr 188f6ef2e50SAndreas Gohr $fetch = ceil( 189f6ef2e50SAndreas Gohr ($this->model->getMaxContextTokenLength() / $this->model->getMaxEmbeddingTokenLength()) 190f6ef2e50SAndreas Gohr * 1.5 // fetch a few more than needed, since not all chunks are maximum length 191f6ef2e50SAndreas Gohr ); 192*aee9b383SAndreas Gohr 193*aee9b383SAndreas Gohr $time = microtime(true); 19468908844SAndreas Gohr $chunks = $this->storage->getSimilarChunks($vector, $fetch); 195*aee9b383SAndreas Gohr if ($this->logger) { 196*aee9b383SAndreas Gohr $this->logger->info( 197*aee9b383SAndreas Gohr 'Fetched {count} similar chunks from store in {time} seconds', 198*aee9b383SAndreas Gohr ['count' => count($chunks), 'time' => round(microtime(true) - $time, 2)] 199*aee9b383SAndreas Gohr ); 200*aee9b383SAndreas Gohr } 20168908844SAndreas Gohr 20268908844SAndreas Gohr $size = 0; 2038817535bSAndreas Gohr $result = []; 2047ee8b02dSAndreas Gohr foreach ($chunks as $chunk) { 2059e81bea7SAndreas Gohr // filter out chunks the user is not allowed to read 2067ee8b02dSAndreas Gohr if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue; 20768908844SAndreas Gohr 20868908844SAndreas Gohr $chunkSize = count($this->getTokenEncoder()->encode($chunk->getText())); 209f6ef2e50SAndreas Gohr if ($size + $chunkSize > $this->model->getMaxContextTokenLength()) break; // we have enough 21068908844SAndreas Gohr 2119e81bea7SAndreas Gohr $result[] = $chunk; 21268908844SAndreas Gohr $size += $chunkSize; 2138817535bSAndreas Gohr } 2148817535bSAndreas Gohr return $result; 2158817535bSAndreas Gohr } 2168817535bSAndreas Gohr 2175786be46SAndreas Gohr 2185786be46SAndreas Gohr /** 2198817535bSAndreas Gohr * @param $text 2208817535bSAndreas Gohr * @return array 2218817535bSAndreas Gohr * @throws \Exception 2228817535bSAndreas Gohr * @todo support splitting too long sentences 2238817535bSAndreas Gohr */ 224ad38c5fdSAndreas Gohr public function splitIntoChunks($text) 2258817535bSAndreas Gohr { 2268817535bSAndreas Gohr $sentenceSplitter = new Sentence(); 22768908844SAndreas Gohr $tiktok = $this->getTokenEncoder(); 2288817535bSAndreas Gohr 2298817535bSAndreas Gohr $chunks = []; 2308817535bSAndreas Gohr $sentences = $sentenceSplitter->split($text); 2318817535bSAndreas Gohr 2328817535bSAndreas Gohr $chunklen = 0; 2338817535bSAndreas Gohr $chunk = ''; 2348817535bSAndreas Gohr while ($sentence = array_shift($sentences)) { 2358817535bSAndreas Gohr $slen = count($tiktok->encode($sentence)); 236f6ef2e50SAndreas Gohr if ($slen > $this->model->getMaxEmbeddingTokenLength()) { 2378817535bSAndreas Gohr // sentence is too long, we need to split it further 238ad38c5fdSAndreas Gohr if ($this->logger) $this->logger->warning('Sentence too long, splitting not implemented yet'); 239ad38c5fdSAndreas Gohr continue; 2408817535bSAndreas Gohr } 2418817535bSAndreas Gohr 242f6ef2e50SAndreas Gohr if ($chunklen + $slen < $this->model->getMaxEmbeddingTokenLength()) { 2438817535bSAndreas Gohr // add to current chunk 2448817535bSAndreas Gohr $chunk .= $sentence; 2458817535bSAndreas Gohr $chunklen += $slen; 24668908844SAndreas Gohr // remember sentence for overlap check 24768908844SAndreas Gohr $this->rememberSentence($sentence); 2488817535bSAndreas Gohr } else { 24968908844SAndreas Gohr // add current chunk to result 2508817535bSAndreas Gohr $chunks[] = $chunk; 25168908844SAndreas Gohr 25268908844SAndreas Gohr // start new chunk with remembered sentences 25368908844SAndreas Gohr $chunk = join(' ', $this->sentenceQueue); 25468908844SAndreas Gohr $chunk .= $sentence; 25568908844SAndreas Gohr $chunklen = count($tiktok->encode($chunk)); 2568817535bSAndreas Gohr } 2578817535bSAndreas Gohr } 2588817535bSAndreas Gohr $chunks[] = $chunk; 2598817535bSAndreas Gohr 2608817535bSAndreas Gohr return $chunks; 2618817535bSAndreas Gohr } 26268908844SAndreas Gohr 26368908844SAndreas Gohr /** 26468908844SAndreas Gohr * Add a sentence to the queue of remembered sentences 26568908844SAndreas Gohr * 26668908844SAndreas Gohr * @param string $sentence 26768908844SAndreas Gohr * @return void 26868908844SAndreas Gohr */ 26968908844SAndreas Gohr protected function rememberSentence($sentence) 27068908844SAndreas Gohr { 27168908844SAndreas Gohr // add sentence to queue 27268908844SAndreas Gohr $this->sentenceQueue[] = $sentence; 27368908844SAndreas Gohr 27468908844SAndreas Gohr // remove oldest sentences from queue until we are below the max overlap 27568908844SAndreas Gohr $encoder = $this->getTokenEncoder(); 27668908844SAndreas Gohr while (count($encoder->encode(join(' ', $this->sentenceQueue))) > self::MAX_OVERLAP_LEN) { 27768908844SAndreas Gohr array_shift($this->sentenceQueue); 27868908844SAndreas Gohr } 27968908844SAndreas Gohr } 2808817535bSAndreas Gohr} 281