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 ($skipRE && preg_match($skipRE, $page)) 87 ) { 88 // this page should not be in the index (anymore) 89 $this->storage->deletePageChunks($page, $chunkID); 90 continue; 91 } 92 93 $firstChunk = $this->storage->getChunk($chunkID); 94 if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) { 95 // page is older than the chunks we have, reuse the existing chunks 96 $this->storage->reusePageChunks($page, $chunkID); 97 if($this->logger) $this->logger->info("Reusing chunks for $page"); 98 } else { 99 // page is newer than the chunks we have, create new chunks 100 $this->storage->deletePageChunks($page, $chunkID); 101 $this->storage->addPageChunks($this->createPageChunks($page, $chunkID)); 102 } 103 } 104 $this->storage->finalizeCreation(); 105 } 106 107 /** 108 * Split the given page, fetch embedding vectors and return Chunks 109 * 110 * @param string $page Name of the page to split 111 * @param int $firstChunkID The ID of the first chunk of this page 112 * @return Chunk[] A list of chunks created for this page 113 * @throws \Exception 114 */ 115 protected function createPageChunks($page, $firstChunkID) 116 { 117 $chunkList = []; 118 $parts = $this->splitIntoChunks(rawWiki($page)); 119 foreach ($parts as $part) { 120 try { 121 $embedding = $this->openAI->getEmbedding($part); 122 } catch (\Exception $e) { 123 if ($this->logger) { 124 $this->logger->error( 125 'Failed to get embedding for chunk of page {page}: {msg}', 126 ['page' => $page, 'msg' => $e->getMessage()] 127 ); 128 } 129 continue; 130 } 131 $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding); 132 $firstChunkID++; 133 } 134 if ($this->logger) { 135 $this->logger->success('{id} split into {count} chunks', ['id' => $page, 'count' => count($parts)]); 136 } 137 return $chunkList; 138 } 139 140 /** 141 * Do a nearest neighbor search for chunks similar to the given question 142 * 143 * Returns only chunks the current user is allowed to read, may return an empty result. 144 * 145 * @param string $query The question 146 * @param int $limit The number of results to return 147 * @return Chunk[] 148 * @throws \Exception 149 */ 150 public function getSimilarChunks($query, $limit = 4) 151 { 152 global $auth; 153 $vector = $this->openAI->getEmbedding($query); 154 155 $chunks = $this->storage->getSimilarChunks($vector, $limit); 156 $result = []; 157 foreach ($chunks as $chunk) { 158 // filter out chunks the user is not allowed to read 159 if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue; 160 $result[] = $chunk; 161 if (count($result) >= $limit) break; 162 } 163 return $result; 164 } 165 166 167 /** 168 * @param $text 169 * @return array 170 * @throws \Exception 171 * @todo maybe add overlap support 172 * @todo support splitting too long sentences 173 */ 174 public function splitIntoChunks($text) 175 { 176 $sentenceSplitter = new Sentence(); 177 $tiktok = new Encoder(); 178 179 $chunks = []; 180 $sentences = $sentenceSplitter->split($text); 181 182 $chunklen = 0; 183 $chunk = ''; 184 while ($sentence = array_shift($sentences)) { 185 $slen = count($tiktok->encode($sentence)); 186 if ($slen > self::MAX_TOKEN_LEN) { 187 // sentence is too long, we need to split it further 188 if ($this->logger) $this->logger->warning('Sentence too long, splitting not implemented yet'); 189 continue; 190 } 191 192 if ($chunklen + $slen < self::MAX_TOKEN_LEN) { 193 // add to current chunk 194 $chunk .= $sentence; 195 $chunklen += $slen; 196 } else { 197 // start new chunk 198 $chunks[] = $chunk; 199 $chunk = $sentence; 200 $chunklen = $slen; 201 } 202 } 203 $chunks[] = $chunk; 204 205 return $chunks; 206 } 207} 208