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