1<?php 2 3namespace dokuwiki\plugin\aichat; 4 5use dokuwiki\plugin\aichat\backend\AbstractStorage; 6use dokuwiki\plugin\aichat\backend\Chunk; 7use dokuwiki\plugin\aichat\backend\KDTreeStorage; 8use dokuwiki\plugin\aichat\backend\SQLiteStorage; 9use dokuwiki\Search\Indexer; 10use Hexogen\KDTree\Exception\ValidationException; 11use splitbrain\phpcli\CLI; 12use TikToken\Encoder; 13use Vanderlee\Sentence\Sentence; 14 15/** 16 * Manage the embeddings index 17 * 18 * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from 19 * OpenAI and stored in the Storage backend. 20 */ 21class Embeddings 22{ 23 24 const MAX_TOKEN_LEN = 1000; 25 26 27 /** @var OpenAI */ 28 protected $openAI; 29 /** @var CLI|null */ 30 protected $logger; 31 32 /** @var AbstractStorage */ 33 protected $storage; 34 35 /** 36 * @param OpenAI $openAI 37 */ 38 public function __construct(OpenAI $openAI) 39 { 40 $this->openAI = $openAI; 41 //$this->storage = new KDTreeStorage(); // FIXME make configurable 42 $this->storage = new SQLiteStorage(); // FIXME make configurable 43 } 44 45 /** 46 * Access storage 47 * 48 * @return AbstractStorage 49 */ 50 public function getStorage() 51 { 52 return $this->storage; 53 } 54 55 /** 56 * Add a logger instance 57 * 58 * @param CLI $logger 59 * @return void 60 */ 61 public function setLogger(CLI $logger) 62 { 63 $this->logger = $logger; 64 } 65 66 /** 67 * Update the embeddings storage 68 * 69 * @param string $skipRE Regular expression to filter out pages (full RE with delimiters) 70 * @param bool $clear Should any existing storage be cleared before updating? 71 * @return void 72 * @throws \Exception 73 */ 74 public function createNewIndex($skipRE = '', $clear = false) 75 { 76 $indexer = new Indexer(); 77 $pages = $indexer->getPages(); 78 79 $this->storage->startCreation(1536, $clear); 80 foreach ($pages as $pid => $page) { 81 $chunkID = $pid * 100; // chunk IDs start at page ID * 100 82 83 if ( 84 !page_exists($page) || 85 isHiddenPage($page) || 86 filesize(wikiFN($page)) < 150 || // skip very small pages 87 ($skipRE && preg_match($skipRE, $page)) 88 ) { 89 // this page should not be in the index (anymore) 90 $this->storage->deletePageChunks($page, $chunkID); 91 continue; 92 } 93 94 $firstChunk = $this->storage->getChunk($chunkID); 95 if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) { 96 // page is older than the chunks we have, reuse the existing chunks 97 $this->storage->reusePageChunks($page, $chunkID); 98 if($this->logger) $this->logger->info("Reusing chunks for $page"); 99 } else { 100 // page is newer than the chunks we have, create new chunks 101 $this->storage->deletePageChunks($page, $chunkID); 102 $this->storage->addPageChunks($this->createPageChunks($page, $chunkID)); 103 } 104 } 105 $this->storage->finalizeCreation(); 106 } 107 108 /** 109 * Split the given page, fetch embedding vectors and return Chunks 110 * 111 * @param string $page Name of the page to split 112 * @param int $firstChunkID The ID of the first chunk of this page 113 * @return Chunk[] A list of chunks created for this page 114 * @throws \Exception 115 * @todo support the text renderer 116 */ 117 protected function createPageChunks($page, $firstChunkID) 118 { 119 $chunkList = []; 120 $parts = $this->splitIntoChunks(rawWiki($page)); 121 foreach ($parts as $part) { 122 try { 123 $embedding = $this->openAI->getEmbedding($part); 124 } catch (\Exception $e) { 125 if ($this->logger) { 126 $this->logger->error( 127 'Failed to get embedding for chunk of page {page}: {msg}', 128 ['page' => $page, 'msg' => $e->getMessage()] 129 ); 130 } 131 continue; 132 } 133 $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding); 134 $firstChunkID++; 135 } 136 if ($this->logger) { 137 $this->logger->success('{id} split into {count} chunks', ['id' => $page, 'count' => count($parts)]); 138 } 139 return $chunkList; 140 } 141 142 /** 143 * Do a nearest neighbor search for chunks similar to the given question 144 * 145 * Returns only chunks the current user is allowed to read, may return an empty result. 146 * 147 * @param string $query The question 148 * @param int $limit The number of results to return 149 * @return Chunk[] 150 * @throws \Exception 151 */ 152 public function getSimilarChunks($query, $limit = 4) 153 { 154 global $auth; 155 $vector = $this->openAI->getEmbedding($query); 156 157 $chunks = $this->storage->getSimilarChunks($vector, $limit); 158 $result = []; 159 foreach ($chunks as $chunk) { 160 // filter out chunks the user is not allowed to read 161 if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue; 162 $result[] = $chunk; 163 if (count($result) >= $limit) break; 164 } 165 return $result; 166 } 167 168 169 /** 170 * @param $text 171 * @return array 172 * @throws \Exception 173 * @todo maybe add overlap support 174 * @todo support splitting too long sentences 175 */ 176 public function splitIntoChunks($text) 177 { 178 $sentenceSplitter = new Sentence(); 179 $tiktok = new Encoder(); 180 181 $chunks = []; 182 $sentences = $sentenceSplitter->split($text); 183 184 $chunklen = 0; 185 $chunk = ''; 186 while ($sentence = array_shift($sentences)) { 187 $slen = count($tiktok->encode($sentence)); 188 if ($slen > self::MAX_TOKEN_LEN) { 189 // sentence is too long, we need to split it further 190 if ($this->logger) $this->logger->warning('Sentence too long, splitting not implemented yet'); 191 continue; 192 } 193 194 if ($chunklen + $slen < self::MAX_TOKEN_LEN) { 195 // add to current chunk 196 $chunk .= $sentence; 197 $chunklen += $slen; 198 } else { 199 // start new chunk 200 $chunks[] = $chunk; 201 $chunk = $sentence; 202 $chunklen = $slen; 203 } 204 } 205 $chunks[] = $chunk; 206 207 return $chunks; 208 } 209} 210