1<?php 2 3namespace dokuwiki\plugin\aichat; 4 5use dokuwiki\Extension\PluginInterface; 6use dokuwiki\plugin\aichat\Model\AbstractModel; 7use dokuwiki\plugin\aichat\Storage\AbstractStorage; 8use dokuwiki\Search\Indexer; 9use splitbrain\phpcli\CLI; 10use TikToken\Encoder; 11use Vanderlee\Sentence\Sentence; 12 13/** 14 * Manage the embeddings index 15 * 16 * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from 17 * OpenAI and stored in the Storage backend. 18 */ 19class Embeddings 20{ 21 /** @var int maximum overlap between chunks in tokens */ 22 public const MAX_OVERLAP_LEN = 200; 23 24 /** @var AbstractModel */ 25 protected $model; 26 /** @var CLI|null */ 27 protected $logger; 28 /** @var Encoder */ 29 protected $tokenEncoder; 30 31 /** @var AbstractStorage */ 32 protected $storage; 33 34 /** @var array remember sentences when chunking */ 35 private $sentenceQueue = []; 36 37 /** 38 * @param AbstractModel $model 39 */ 40 public function __construct(AbstractModel $model, AbstractStorage $storage) 41 { 42 $this->model = $model; 43 $this->storage = $storage; 44 } 45 46 /** 47 * Access storage 48 * 49 * @return AbstractStorage 50 */ 51 public function getStorage() 52 { 53 return $this->storage; 54 } 55 56 /** 57 * Add a logger instance 58 * 59 * @param CLI $logger 60 * @return void 61 */ 62 public function setLogger(CLI $logger) 63 { 64 $this->logger = $logger; 65 } 66 67 /** 68 * Get the token encoder instance 69 * 70 * @return Encoder 71 */ 72 public function getTokenEncoder() 73 { 74 if (!$this->tokenEncoder instanceof Encoder) { 75 $this->tokenEncoder = new Encoder(); 76 } 77 return $this->tokenEncoder; 78 } 79 80 /** 81 * Update the embeddings storage 82 * 83 * @param string $skipRE Regular expression to filter out pages (full RE with delimiters) 84 * @param bool $clear Should any existing storage be cleared before updating? 85 * @return void 86 * @throws \Exception 87 */ 88 public function createNewIndex($skipRE = '', $clear = false) 89 { 90 $indexer = new Indexer(); 91 $pages = $indexer->getPages(); 92 93 $this->storage->startCreation($clear); 94 foreach ($pages as $pid => $page) { 95 $chunkID = $pid * 100; // chunk IDs start at page ID * 100 96 97 if ( 98 !page_exists($page) || 99 isHiddenPage($page) || 100 filesize(wikiFN($page)) < 150 || // skip very small pages 101 ($skipRE && preg_match($skipRE, $page)) 102 ) { 103 // this page should not be in the index (anymore) 104 $this->storage->deletePageChunks($page, $chunkID); 105 continue; 106 } 107 108 $firstChunk = $this->storage->getChunk($chunkID); 109 if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) { 110 // page is older than the chunks we have, reuse the existing chunks 111 $this->storage->reusePageChunks($page, $chunkID); 112 if ($this->logger instanceof CLI) $this->logger->info("Reusing chunks for $page"); 113 } else { 114 // page is newer than the chunks we have, create new chunks 115 $this->storage->deletePageChunks($page, $chunkID); 116 $this->storage->addPageChunks($this->createPageChunks($page, $chunkID)); 117 } 118 } 119 $this->storage->finalizeCreation(); 120 } 121 122 /** 123 * Split the given page, fetch embedding vectors and return Chunks 124 * 125 * Will use the text renderer plugin if available to get the rendered text. 126 * Otherwise the raw wiki text is used. 127 * 128 * @param string $page Name of the page to split 129 * @param int $firstChunkID The ID of the first chunk of this page 130 * @return Chunk[] A list of chunks created for this page 131 * @throws \Exception 132 */ 133 protected function createPageChunks($page, $firstChunkID) 134 { 135 $chunkList = []; 136 137 $textRenderer = plugin_load('renderer', 'text'); 138 if ($textRenderer instanceof PluginInterface) { 139 global $ID; 140 $ID = $page; 141 $text = p_cached_output(wikiFN($page), 'text', $page); 142 } else { 143 $text = rawWiki($page); 144 } 145 146 $parts = $this->splitIntoChunks($text); 147 foreach ($parts as $part) { 148 if (trim($part) == '') continue; // skip empty chunks 149 150 try { 151 $embedding = $this->model->getEmbedding($part); 152 } catch (\Exception $e) { 153 if ($this->logger instanceof CLI) { 154 $this->logger->error( 155 'Failed to get embedding for chunk of page {page}: {msg}', 156 ['page' => $page, 'msg' => $e->getMessage()] 157 ); 158 } 159 continue; 160 } 161 $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding); 162 $firstChunkID++; 163 } 164 if ($this->logger instanceof CLI) { 165 if ($chunkList !== []) { 166 $this->logger->success('{id} split into {count} chunks', ['id' => $page, 'count' => count($chunkList)]); 167 } else { 168 $this->logger->warning('{id} could not be split into chunks', ['id' => $page]); 169 } 170 } 171 return $chunkList; 172 } 173 174 /** 175 * Do a nearest neighbor search for chunks similar to the given question 176 * 177 * Returns only chunks the current user is allowed to read, may return an empty result. 178 * The number of returned chunks depends on the MAX_CONTEXT_LEN setting. 179 * 180 * @param string $query The question 181 * @param string $lang Limit results to this language 182 * @return Chunk[] 183 * @throws \Exception 184 */ 185 public function getSimilarChunks($query, $lang = '') 186 { 187 global $auth; 188 $vector = $this->model->getEmbedding($query); 189 190 $fetch = ceil( 191 ($this->model->getMaxContextTokenLength() / $this->model->getMaxEmbeddingTokenLength()) 192 * 1.5 // fetch a few more than needed, since not all chunks are maximum length 193 ); 194 195 $time = microtime(true); 196 $chunks = $this->storage->getSimilarChunks($vector, $lang, $fetch); 197 if ($this->logger instanceof CLI) { 198 $this->logger->info( 199 'Fetched {count} similar chunks from store in {time} seconds', 200 ['count' => count($chunks), 'time' => round(microtime(true) - $time, 2)] 201 ); 202 } 203 204 $size = 0; 205 $result = []; 206 foreach ($chunks as $chunk) { 207 // filter out chunks the user is not allowed to read 208 if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue; 209 210 $chunkSize = count($this->getTokenEncoder()->encode($chunk->getText())); 211 if ($size + $chunkSize > $this->model->getMaxContextTokenLength()) break; // we have enough 212 213 $result[] = $chunk; 214 $size += $chunkSize; 215 } 216 return $result; 217 } 218 219 220 /** 221 * @param $text 222 * @return array 223 * @throws \Exception 224 * @todo support splitting too long sentences 225 */ 226 public function splitIntoChunks($text) 227 { 228 $sentenceSplitter = new Sentence(); 229 $tiktok = $this->getTokenEncoder(); 230 231 $chunks = []; 232 $sentences = $sentenceSplitter->split($text); 233 234 $chunklen = 0; 235 $chunk = ''; 236 while ($sentence = array_shift($sentences)) { 237 $slen = count($tiktok->encode($sentence)); 238 if ($slen > $this->model->getMaxEmbeddingTokenLength()) { 239 // sentence is too long, we need to split it further 240 if ($this->logger instanceof CLI) $this->logger->warning('Sentence too long, splitting not implemented yet'); 241 continue; 242 } 243 244 if ($chunklen + $slen < $this->model->getMaxEmbeddingTokenLength()) { 245 // add to current chunk 246 $chunk .= $sentence; 247 $chunklen += $slen; 248 // remember sentence for overlap check 249 $this->rememberSentence($sentence); 250 } else { 251 // add current chunk to result 252 $chunks[] = $chunk; 253 254 // start new chunk with remembered sentences 255 $chunk = implode(' ', $this->sentenceQueue); 256 $chunk .= $sentence; 257 $chunklen = count($tiktok->encode($chunk)); 258 } 259 } 260 $chunks[] = $chunk; 261 262 return $chunks; 263 } 264 265 /** 266 * Add a sentence to the queue of remembered sentences 267 * 268 * @param string $sentence 269 * @return void 270 */ 271 protected function rememberSentence($sentence) 272 { 273 // add sentence to queue 274 $this->sentenceQueue[] = $sentence; 275 276 // remove oldest sentences from queue until we are below the max overlap 277 $encoder = $this->getTokenEncoder(); 278 while (count($encoder->encode(implode(' ', $this->sentenceQueue))) > self::MAX_OVERLAP_LEN) { 279 array_shift($this->sentenceQueue); 280 } 281 } 282} 283