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